#!/bin/bash
#./calico.sh node https://192.168.1.206 https://192.168.1.208:2379,https://192.168.1.206:2379,https://192.168.1.207:2379
NAME=${1:-"master"}
IP_ADDRESS=${2:-"https://192.168.1.208"}
ETCD_IPADDRESS=${3:-"https://192.168.1.208 https://192.168.1.208:2379,https://192.168.1.206:2379,https://192.168.1.207:2379"}
yum install -y ipvsadm ipset bridge-utils
cat >/usr/local/kubernetes/cfg/calico <<EOF
CALICO_NODENAME="${NAME}" \\
ETCD_ENDPOINTS=${ETCD_IPADDRESS} \\
ETCD_CA_CERT_FILE="/usr/local/kubernetes/ssl/ca.pem" \\
ETCD_CERT_FILE="/usr/local/kubernetes/ssl/etcd.pem" \\
ETCD_KEY_FILE="/usr/local/kubernetes/ssl/etcd-key.pem" \\
CALICO_IP="${IP_ADDRESS}" \\
CALICO_AS="65142" \\
CALICO_LIBNETWORK_ENABLED=true \\
CALICO_NETWORKING_BACKEND=bird \\
FELIX_IPV6SUPPORT=false \\
FELIX_DEFAULTENDPOINTTOHOSTACTION=ACCEPT \\
FELIX_LOGSEVERITYSCREEN=info 
EOF
cat >/etc/cni/net.d/10-calico.conf <<EOF
{
    "name": "calico-k8s-network",
    "cniVersion": "0.3.0",
    "type": "calico",
    "etcd_endpoints": "${ETCD_IPADDRESS}",
    "etcd_key_file": "/usr/local/kubernetes/ssl/etcd-key.pem",
    "etcd_cert_file": "/usr/local/kubernetes/ssl/etcd.pem",
    "etcd_ca_cert_file": "/usr/local/kubernetes/ssl/ca.pem",
    "log_level": "info",
    "mtu": 1500,
    "ipam": {
        "type": "calico-ipam"
    },
    "policy": {
        "type": "k8s"
    },
    "kubernetes": {
        "kubeconfig": "/usr/local/kubernetes/cfg/kubelet"
    }
}
EOF

cat > /lib/systemd/system/calico.service <<EOF
[Unit]
Description=calico-node
After=docker.service
Requires=docker.service
 
[Service]
User=root
PermissionsStartOnly=true
EnvironmentFile=/usr/local/kubernetes/cfg/calico
ExecStart=/usr/bin/docker run --net=host --privileged --name=calico-node \\
 -e NODENAME=${CALICO_NODENAME} \\
 -e ETCD_ENDPOINTS=${ETCD_ENDPOINTS} \\
 -e ETCD_CA_CERT_FILE=${ETCD_CA_CERT_FILE} \\
 -e ETCD_CERT_FILE=${ETCD_CERT_FILE} \\
 -e ETCD_KEY_FILE=${ETCD_KEY_FILE} \\
 -e IP=${CALICO_IP} \\
 -e AS=${CALICO_AS} \\
 -e CALICO_LIBNETWORK_ENABLED=${CALICO_LIBNETWORK_ENABLED} \\
 -e CALICO_NETWORKING_BACKEND=${CALICO_NETWORKING_BACKEND} \\
 -e FELIX_IPV6SUPPORT=${FELIX_IPV6SUPPORT} \
 -e FELIX_DEFAULTENDPOINTTOHOSTACTION=${FELIX_DEFAULTENDPOINTTOHOSTACTION} \\
 -e FELIX_LOGSEVERITYSCREEN=${FELIX_LOGSEVERITYSCREEN} \\
 -v /usr/local/kubernetes/ssl/ca.pem:/usr/local/kubernetes/ssl/ca.pem \\
 -v /usr/local/kubernetes/ssl/etcd.pem:/usr/local/kubernetes/ssl/etcd.pem \\
 -v /usr/local/kubernetes/ssl/etcd-key.pem:/usr/local/kubernetes/ssl/etcd-key.pem \\
 -v /run/docker/plugins:/run/docker/plugins \\
 -v /lib/modules:/lib/modules \\
 -v /var/run/calico:/var/run/calico \\
 -v /var/log/calico:/var/log/calico \\
 -v /var/lib/calico:/var/lib/calico \\
 quay.io/calico/node:v3.3.1
 
ExecStop=/usr/bin/docker rm -f calico-node
Restart=always
RestartSec=10
 
[Install]
WantedBy=multi-user.target
EOF
